<?php
declare (strict_types = 1);
namespace app\api\controller;

use think\Request;
use app\BaseController;
use think\facade\{Db, Log};
use think\exception\ValidateException;

use app\api\validate\{UsersValidate, AdminValidate, GoodsValidate, CateValidate, GoodsGroupValidate};
use app\api\model\{Cate, Admin, Users, Banner, Goods, GoodsGroup, GoodsImg, UserShop, OrderGroup};

class HomeController extends BaseController
{
    /**
	 * 轮播图列表
	 */
    public function getBannerLists()
    {
        if(request()->isPost()){
            $bannerModel = new Banner();
            $field = 'id, img';
            $list = $bannerModel->getList(['is_show' => 1], $field);

            if($list['code'] != 'ok'){
                $this->error_back($list['msg']);
            }

            $this->success_back('ok', $list['data']);
        }
    }

    /**
	 * 分类列表
	 */
    public function getCateLists()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(CateValidate::class)->scene('type')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $cateModel = new Cate();
            $field = 'id, name';
            $list = $cateModel->getList(['type' => $data['type']], 0, 0, 0, $field);

            if($list['code'] != 'ok'){
                $this->error_back($list['msg']);
            }

            $this->success_back('ok', $list['data']);
        }
    }

    /**
	 * 商品列表
	 */
    public function getGoodsLists()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(GoodsValidate::class)->scene('list')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            // 获取商品列表
            $goodsModel = new Goods();

            $where = [
                ['admin_id', '=', $data['admin_id']],
                ['status', '=', 1],
                ['del_time', '=', 0],
            ];

            if($data['type'] != 0){
                $where[] = ['type', '=', $data['type']];
            }

            if($data['cate_id'] != 0){
                $where[] = ['cate_id', '=', $data['cate_id']];
            }
            
            $field = 'id, title, subtitile, price, price_original, small_img';
            $list = $goodsModel->getList($where, 1, $data['curr'], $data['limit'], $field, 'sell_number DESC');

            if($list['code'] != 'ok'){
                $this->error_back($list['msg']);
            }

            $this->success_back('ok', $list['data']);
        }
    }

    /**
	 * 商品详情
	 */
    public function getGoodsShow()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(GoodsValidate::class)->scene('show')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $goodsModel = new Goods();

            $where = ['id' => $data['goods_id']];

            $info = $goodsModel->getGoodsShow($data['goods_id']);

            if($info['code'] != 'ok'){
                $this->error_back($info['msg']);
            }

            if($info['data']['type'] == 3){
                $back_info = [
                    'id'             => $info['data']['id'],
                    'title'          => $info['data']['title'],
                    'subtitile'      => $info['data']['subtitile'],
                    'small_img'      => $info['data']['small_img'],
                    'price'          => $info['data']['price'],
                    'price_original' => $info['data']['price_original'],
                    'number'         => $info['data']['number'],
                    'use_days'       => $info['data']['use_days'],
                    'is_discount'    => $info['data']['is_discount'],
                    'img'            => $info['data']['img'],
                ];
            }else{
                $back_info = [
                    'id'             => $info['data']['id'],
                    'title'          => $info['data']['title'],
                    'subtitile'      => $info['data']['subtitile'],
                    'small_img'      => $info['data']['small_img'],
                    'price'          => $info['data']['price'],
                    'price_original' => $info['data']['price_original'],
                    'is_discount'    => $info['data']['is_discount'],
                    'img'            => $info['data']['img'],
                ];
            }

            $this->success_back('ok', $back_info);
        }
    }

    /**
	 * 团购商品列表
	 */
    public function getGroupLists()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(GoodsGroupValidate::class)->scene('list')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $goodsModel = new Goods();
            $groupModel = new GoodsGroup();

            $where = [
                ['admin_id', '=', $data['admin_id']],
                ['del_time', '=', 0],
            ];

            $field = 'id, goods_id, price_only, price_sec, price_thi, price_original, group_time, create_time';
            $list = $groupModel->getList($where, 1, $data['curr'], $data['limit'], $field);

            if($list['code'] != 'ok'){
                $this->error_back($list['msg']);
            }
            
            foreach($list['data'] as $k => &$v){
                $goods_info = $goodsModel->getFind(['id' => $v['goods_id']]);

                if($goods_info['code'] != 'ok'){
                    unset($list['data'][$k]);
                    continue;
                }

                $v['title']      = $goods_info['data']['title'];
                $v['subtitile']  = $goods_info['data']['subtitile'];
                $v['small_img']  = $goods_info['data']['small_img'];
                $v['group_time'] = $v->getData('create_time') + $v['group_time'] * 86400 - time();
                unset($v['create_time']);
            }

            $this->success_back('ok', $list['data']);
        }
    }

    /**
	 * 团购商品详情
	 */
    public function getGroupShow()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(GoodsGroupValidate::class)->scene('show')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $userModel = new Users();
            $goodsModel = new Goods();
            $groupModel = new GoodsGroup();
            $orderGroupModel = new OrderGroup();

            $where = ['id' => $data['group_id']];
            $field = 'id, admin_id, goods_id, price_sec, price_only, price_thi, price_original, create_time, group_time';
            $info = $groupModel->getGroupShow($data['group_id'], $field);

            if($info['code'] != 'ok'){
                $this->error_back($info['msg']);
            }

            $goods_info = $goodsModel->getFind(['id' => $info['data']['goods_id']]);

            $info['data']['title']      = $goods_info['data']['title'];
            $info['data']['subtitile']  = $goods_info['data']['subtitile'];
            $info['data']['small_img']  = $goods_info['data']['small_img'];
            $info['data']['group_time'] = $info['data']->getData('create_time') + $info['data']['group_time'] * 86400 - time();
            unset($info['data']['create_time']);

            /** 查询商品的拼团列表 */
            $order_group_list = $orderGroupModel->getList(['group_id' => $data['group_id'], 'admin_id' => $info['data']['admin_id'], 'status' => 2, 'chief_id' => 0], 0);

            /** 拼团信息 */
            $chief_arr = [];

            if($order_group_list['code'] != 'ok'){
                $this->success_back('ok', $info['data']);
            }

            foreach($order_group_list['data'] as $k => &$v){
                /** 查询当前拼团的参团人ids */
                $chief_user_ids = $orderGroupModel->getCol(['chief_id' => $v['user_id'], 'status' => 2], 'user_id')['data'];

                /** 团长的id插入参团人ids头部 */
                array_unshift($chief_user_ids, $v['user_id']);

                /** 获取拼团人信息 */
                $chief_user_list = $userModel->getList([['id', 'in', $chief_user_ids]], 0, 0, 0, 'head_img, phone');

                if($chief_user_list['code'] != 'ok'){
                    unset($v);
                    continue;
                }

                $chief_info = [
                    'id'               => $v['user_id'],
                    'order_id'         => $v['id'],
                    'chief_number'     => $v['chief_number'],
                    'chief_number_now' => count($chief_user_ids),
                    'status'           => $v['status'],
                    'list'             => $chief_user_list['data']
                ];

                $chief_arr[] = $chief_info;
            }

            $info['data']['chief_arr'] = $chief_arr;

            $this->success_back('ok', $info['data']);
        }
    }

    /**
	 * 店铺列表
	 */
    public function getShopList()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(AdminValidate::class)->scene('list')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $adminModel = new Admin();

            // 获取店铺列表
            $where = ['role_id' => 2, 'del_time' => 0];
            $field = 'id, logo, nickname, longitude, latitude, concat(region, "-" ,address) as address, is_business';

            $list = $adminModel->getList($where, 1, $data['curr'], $data['limit'], $field);

            if($list['code'] != 'ok'){
                $this->error_back($list['msg']);
            }

            foreach($list['data'] as $k => $v){
                $list['data'][$k]['distance'] = getDistance($data['latitude'], $data['longitude'], $v['latitude'], $v['longitude']);
            }

            $this->success_back('ok', $list['data']);
        }
    }

    /**
	 * 店铺详情
	 */
    public function getShopShow()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(AdminValidate::class)->scene('show')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $adminModel = new Admin();

            $field = 'id, logo, nickname, longitude, latitude, is_business, concat(region, "-" ,address) as address, status';
            $shop_info = $adminModel->getFind(['id' => $data['admin_id']], $field);

            if($shop_info['code'] != 'ok'){
                $this->error_back('获取失败');
            }

            $this->success_back('ok', $shop_info);
        }
    }

    /**
	 * 绑定店铺
	 */
    // public function setBindshop()
    // {
    //     if(request()->isPost()){
    //         $data = input('post.');

    //         // 验证数据
    //         try{
    //             validate(UsersValidate::class)->scene('bind')->check($data);
    //         }catch(ValidateException $e){
    //             $this->error_back($e->getError());
    //         }

    //         /** 修改用户绑定店铺 */
    //         $flag = Users::update(['id' => $data['user_id'], 'bind_admin_id' => $data['admin_id']]);

    //         if(!$flag){
    //             $this->error_back('绑定失败');
    //         }

    //         $userShopModel = new UserShop();

    //         /** 查询系统参数 */
    //         $system = getSystemVal();

    //         /** 查询店铺信息 */
    //         $admin_info = Db::name('admin')->where(['id' => $data['admin_id']])->find();

    //         /** 查询是否首次绑定 */
    //         $userShopArr = ['user_id' => $data['user_id'], 'admin_id' => $data['admin_id']];
    //         $userShopInfo = $userShopModel->getFind($userShopArr);

    //         if($userShopInfo['code'] != 'ok'){
    //             /** 查询用户信息 */
    //             $user_info = Db::name('users')->where(['id' => $data['user_id']])->find();

    //             /** 新人赠送体验金 */
    //             if($system['push_number'] == 0){
    //                 $userShopArr['money_gold']    = $admin_info['money_gold'];
    //                 $userShopArr['is_money_gold'] = 1;
                    
    //                 if($admin_info['gold_time'] > 0){
    //                     $userShopArr['gold_time'] = time() + $admin_info['gold_time'] * 86400;
    //                 }
    //             }else{
    //                 /** 查询用户上级资产信息 */
    //                 $user_shop_up_info = Db::name('user_shop')->where(['user_id' => $user_info['pid'], 'admin_id' => $data['admin_id']])->find();

    //                 /** 查询用户上级拉新人数 */
    //                 $user_push_num = Db::name('users')->where(['pid' => $user_info['pid']])->count();

    //                 /** 给用户上级赠送体验金 */
    //                 if($user_push_num >= $system['push_number'] && $user_shop_up_info['is_money_gold'] == 0){

    //                     if($admin_info['gold_time'] > 0){
    //                         $gold_time = time() + $admin_info['gold_time'] * 86400;
    //                     }

    //                     $money_gold_up_arr = [
    //                         'money_gold'    => $admin_info['money_gold'],
    //                         'is_money_gold' => 1,
    //                         'gold_time'     => $gold_time
    //                     ];

    //                     Db::name('user_shop')->where(['user_id' => $user_info['pid'], 'admin_id' => $data['admin_id']])->update($money_gold_up_arr);
    //                 }
    //             }

    //             /** 首次绑定初始化在当前店铺的资产信息 */
    //             $userShopModel->add($userShopArr);

    //             if($user_info['pid']){
    //                 /** 公众号消息提醒 */
    //                 $newsController = new NewsController($this->app);
    //                 $newsController->news_activate($user_info['pid'], $data['user_id'], $data['admin_id']);
    //             }
    //         }

    //         $this->success_back('成功');
    //     }
    // }

    /**
	 * 绑定店铺
	 */
    public function setBindshop()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(UsersValidate::class)->scene('bind')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            /** 修改用户绑定店铺 */
            $flag = Users::update(['id' => $data['user_id'], 'bind_admin_id' => $data['admin_id']]);

            if(!$flag){
                $this->error_back('绑定失败');
            }

            $userShopModel = new UserShop();

            /** 查询系统参数 */
            $system = getSystemVal();

            /** 查询店铺信息 */
            $admin_info = Db::name('admin')->where(['id' => $data['admin_id']])->find();

            /** 查询是否首次绑定 */
            $userShopArr = ['user_id' => $data['user_id'], 'admin_id' => $data['admin_id']];
            $userShopInfo = $userShopModel->getFind($userShopArr);

            if($userShopInfo['code'] != 'ok'){
                /** 查询用户信息 */
                $user_info = Db::name('users')->where(['id' => $data['user_id']])->find();

                if($user_info['pid'] > 0){
                    /** 查询用户推荐人信息 */
                    $up_user_info = Db::name('users')->where(['id' => $user_info['pid']])->find();

                    /** 新人赠送体验金 */
                    if($up_user_info['type'] == 1){
                        $userShopArr['money_gold']    = $admin_info['money_gold'];
                        $userShopArr['is_money_gold'] = 1;
                        
                        if($admin_info['gold_time'] > 0){
                            $userShopArr['gold_time'] = time() + $admin_info['gold_time'] * 86400;
                        }
                    }else if($up_user_info['type'] == 2 && $system['is_push'] == 0){
                        $userShopArr['money_gold']    = $admin_info['money_gold'];
                        $userShopArr['is_money_gold'] = 1;
                        
                        if($admin_info['gold_time'] > 0){
                            $userShopArr['gold_time'] = time() + $admin_info['gold_time'] * 86400;
                        }
                    }
                    
                    /** 查询用户上级资产信息 */
                    $user_shop_up_info = Db::name('user_shop')->where(['user_id' => $user_info['pid'], 'admin_id' => $data['admin_id']])->find();

                    /** 给用户上级赠送体验金 */
                    if($user_shop_up_info['is_money_gold'] == 0){
                        $gold_time = 0;
                        
                        if($admin_info['gold_time'] > 0){
                            $gold_time = time() + $admin_info['gold_time'] * 86400;
                        }

                        $money_gold_up_arr = [
                            'money_gold'    => $admin_info['money_gold'],
                            'is_money_gold' => 1,
                            'gold_time'     => $gold_time
                        ];

                        Db::name('user_shop')->where(['user_id' => $user_info['pid'], 'admin_id' => $data['admin_id']])->update($money_gold_up_arr);
                    }
                }

                /** 首次绑定初始化在当前店铺的资产信息 */
                $userShopModel->add($userShopArr);

                if($user_info['pid']){
                    /** 公众号消息提醒 */
                    $newsController = new NewsController($this->app);
                    $newsController->news_activate($user_info['pid'], $data['user_id'], $data['admin_id']);
                }
            }

            $this->success_back('成功');
        }
    }
}